import os
from copy import deepcopy

from app.settings import BASE_DIR
from utils import write_file, read_from_file, clean_path

nginx_service_module = read_from_file("{}/deploy/module/nginx/nginx.service".format(BASE_DIR))
nginx_conf_module = read_from_file("{}/deploy/module/nginx/nginx.conf".format(BASE_DIR))
lb_conf_module = read_from_file("{}/deploy/module/nginx/lb-stream.conf".format(BASE_DIR))

NGINX_SERVER_NAME = "nginx.service"
NGINX_CONF_NAME = "nginx.conf"

NGINX_HTTP_CONFIG_DIR = "http_sites"
NGINX_STREAM_CONFIG_DIR = "up_streams"

HTTP_EMPTY_CONF = "http-site-config-set-in-here"
STREAM_EMPTY_CONF = "up-stream-config-set-in-here"


def gen_nginx_service(out_dir, application_dir):
    nginx_service = deepcopy(nginx_service_module)

    nginx_service = nginx_service.format(
        nginx_config_path=clean_path(application_dir + "/nginx/conf/nginx.conf"),
        nginx_pid_path=clean_path(application_dir + "/nginx/logs/nginx.pid")
    )

    path = clean_path(out_dir + "/" + NGINX_SERVER_NAME)
    write_file(path, nginx_service)
    return path


def gen_nginx_conf(out_dir):
    nginx_conf = deepcopy(nginx_conf_module)
    nginx_conf = nginx_conf.format(
        http_config_dir=NGINX_HTTP_CONFIG_DIR,
        stream_config_dir=NGINX_STREAM_CONFIG_DIR,
    )

    path = clean_path(out_dir + "/" + NGINX_CONF_NAME)
    write_file(path, nginx_conf)
    return path


def gen_empty_conf(out_dir):
    path = clean_path(out_dir + "/empty.conf")
    write_file(path, "")
    return path


def gen_nginx_stream_config(out_dir, upstream_name, server_list, lb_port, conf_name):
    lb_config = deepcopy(lb_conf_module)

    proxy = ("\n" + " " * 4).join(["server {};".format(server) for server in server_list])

    lb_config = lb_config.format(
        proxy=proxy,
        lb_port=lb_port,
        upstream_name=upstream_name
    )

    path = os.path.join(out_dir, conf_name)
    write_file(path, lb_config)
    return path
